package cn.powerone.web.controller.autotest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import cn.powerone.common.annotation.Log;
import cn.powerone.common.core.controller.BaseController;
import cn.powerone.common.core.domain.AjaxResult;
import cn.powerone.common.core.page.PageDomain;
import cn.powerone.common.core.page.TableDataInfo;
import cn.powerone.common.core.page.TableSupport;
import cn.powerone.common.enums.BusinessType;
import cn.powerone.common.utils.poi.ExcelUtil;
import cn.powerone.autotest.domain.Project;
import cn.powerone.autotest.domain.ProjectMember;
import cn.powerone.autotest.service.IProjectService;
import cn.powerone.autotest.service.IProjectMemberService;

/**
 * 项目管理Controller (管理端)
 * 
 * @author autotest
 */
@RestController
@RequestMapping("/admin/autotest/projects")
public class AdminProjectController extends BaseController
{
    @Autowired
    private IProjectService projectService;
    
    @Autowired
    private IProjectMemberService projectMemberService;

    /**
     * 获取项目列表
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:list')")
    @GetMapping
    public Map<String, Object> list(Project project) {
        startPage();
        List<Project> list = projectService.selectProjectList(project);
        
        // 获取分页信息
        PageInfo<Project> pageInfo = new PageInfo<>(list);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        
        // 创建符合Schema的响应结构
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> pagination = new HashMap<>();
        
        // 转换项目列表字段名
        List<Map<String, Object>> items = new ArrayList<>();
        for (Project p : list) {
            Map<String, Object> projectItem = new HashMap<>();
            projectItem.put("id", p.getProjectId());
            projectItem.put("name", p.getProjectName());
            projectItem.put("description", p.getDescription());
            // 转换状态值为字符串类型
            projectItem.put("status", p.getStatus().equals("1") ? "active" : "inactive");
            projectItem.put("created_at", p.getCreateTime());
            projectItem.put("updated_at", p.getUpdateTime());
            items.add(projectItem);
        }
        
        // 设置分页数据
        pagination.put("total", pageInfo.getTotal());
        pagination.put("page", pageDomain.getPageNum());
        pagination.put("page_size", pageDomain.getPageSize());
        pagination.put("items", items);
        
        data.put("pagination", pagination);
        
        // 设置基础响应
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", data);
        
        return response;
    }

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:export')")
    @Log(title = "项目管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Project project)
    {
        List<Project> list = projectService.selectProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        return util.exportExcel(list, "项目数据");
    }

    /**
     * 获取项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:query')")
    @GetMapping("/{projectId}")
    public Map<String, Object> getInfo(@PathVariable("projectId") String projectId)
    {
        Project project = projectService.selectProjectById(projectId);
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> projectItem = new HashMap<>();
        
        // 转换项目字段名和状态值
        projectItem.put("id", project.getProjectId());
        projectItem.put("name", project.getProjectName());
        projectItem.put("description", project.getDescription());
        projectItem.put("status", project.getStatus().equals("1") ? "active" : "inactive");
        projectItem.put("created_at", project.getCreateTime());
        projectItem.put("updated_at", project.getUpdateTime());
        
        data.put("project", projectItem);
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", data);
        
        return response;
    }
    
    /**
     * 更新项目信息
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:edit')")
    @Log(title = "项目管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{projectId}")
    public Map<String, Object> update(@PathVariable("projectId") String projectId, @RequestBody Map<String, Object> projectData)
    {
        Project project = new Project();
        project.setProjectId(projectId);
        
        // 从请求体中获取更新字段
        if (projectData.containsKey("name")) {
            project.setProjectName((String) projectData.get("name"));
        }
        if (projectData.containsKey("description")) {
            project.setDescription((String) projectData.get("description"));
        }
        if (projectData.containsKey("status")) {
            String status = (String) projectData.get("status");
            project.setStatus("active".equals(status) ? "1" : "0");
        }
        
        // 检查项目名称唯一性
        if (!projectService.checkProjectNameUnique(project)) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", "项目名称已存在");
            return response;
        }
        
        // 执行更新操作
        projectService.updateProject(project);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", new HashMap<>());
        
        return response;
    }
    
    /**
     * 删除项目
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:remove')")
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectId}")
    public Map<String, Object> delete(@PathVariable("projectId") String projectId)
    {
        projectService.deleteProjectById(projectId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", new HashMap<>());
        
        return response;
    }
    
    /**
     * 获取项目成员列表
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:query')")
    @GetMapping("/{projectId}/members")
    public Map<String, Object> getMembers(@PathVariable("projectId") String projectId)
    {
        List<ProjectMember> members = projectMemberService.selectProjectMembersByProjectId(projectId);
        
        // 创建符合Schema的响应结构
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> pagination = new HashMap<>();
        List<Map<String, Object>> items = new ArrayList<>();
        
        // 转换成员列表字段名
        for (ProjectMember member : members) {
            Map<String, Object> memberItem = new HashMap<>();
            memberItem.put("id", member.getId());
            memberItem.put("project_id", member.getProjectId());
            memberItem.put("user_id", member.getUserId());
            memberItem.put("role", member.getRole());
            memberItem.put("joined_at", member.getJoinedAt());
            memberItem.put("user_name", member.getUserName());
            memberItem.put("nick_name", member.getNickName());
            items.add(memberItem);
        }
        
        // 设置分页数据
        pagination.put("total", items.size());
        pagination.put("page", 1);
        pagination.put("page_size", items.size());
        pagination.put("items", items);
        
        data.put("pagination", pagination);
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", data);
        
        return response;
    }
    
    /**
     * 添加项目成员
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:edit')")
    @Log(title = "项目管理", businessType = BusinessType.INSERT)
    @PostMapping("/{projectId}/members")
    public Map<String, Object> addMember(@PathVariable("projectId") String projectId, @RequestBody Map<String, Object> memberData)
    {
        ProjectMember member = new ProjectMember();
        member.setProjectId(projectId);
        member.setUserId((String) memberData.get("user_id"));
        member.setRole((String) memberData.get("role"));
        
        // 执行添加操作
        projectMemberService.insertProjectMember(member);
        
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> memberItem = new HashMap<>();
        
        // 转换成员字段名
        memberItem.put("id", member.getId());
        memberItem.put("project_id", member.getProjectId());
        memberItem.put("user_id", member.getUserId());
        memberItem.put("role", member.getRole());
        memberItem.put("joined_at", member.getJoinedAt());
        memberItem.put("user_name", member.getUserName());
        memberItem.put("nick_name", member.getNickName());
        
        data.put("member", memberItem);
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", data);
        
        return response;
    }
    
    /**
     * 更新项目成员角色
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:edit')")
    @Log(title = "项目管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{projectId}/members/{userId}")
    public Map<String, Object> updateMemberRole(@PathVariable("projectId") String projectId, 
                                              @PathVariable("userId") String userId, 
                                              @RequestBody Map<String, Object> roleData)
    {
        ProjectMember member = new ProjectMember();
        member.setProjectId(projectId);
        member.setUserId(userId);
        member.setRole((String) roleData.get("role"));
        
        // 执行更新操作
        projectMemberService.updateProjectMemberRole(member);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", new HashMap<>());
        
        return response;
    }
    
    /**
     * 移除项目成员
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:remove')")
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectId}/members/{userId}")
    public Map<String, Object> removeMember(@PathVariable("projectId") String projectId, 
                                          @PathVariable("userId") String userId)
    {
        projectMemberService.deleteProjectMember(projectId, userId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", new HashMap<>());
        
        return response;
    }

    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:add')")
    @Log(title = "项目管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Project project)
    {
        if (!projectService.checkProjectNameUnique(project))
        {
            return AjaxResult.error("新增项目'" + project.getProjectName() + "'失败，项目名称已存在");
        }
        return toAjax(projectService.insertProject(project));
    }

    /**
     * 修改项目 (兼容旧API)
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:edit')")
    @Log(title = "项目管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody Project project)
    {
        if (!projectService.checkProjectNameUnique(project))
        {
            return AjaxResult.error("修改项目'" + project.getProjectName() + "'失败，项目名称已存在");
        }
        return toAjax(projectService.updateProject(project));
    }

    /**
     * 删除项目 (兼容旧API)
     */
    @PreAuthorize("@ss.hasPermi('autotest:project:remove')")
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(String[] projectIds)
    {
        projectService.deleteProjectByIds(projectIds);
        return success();
    }
}